﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeSoft.Application.Bussiness;
using LeSoft.Application.Entity;
using LeSoft.Application.Cache;
using LeSoft.Util;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Util;
using ZXing;
using LeSoft.Application.Code;
using System.Text;
using Newtonsoft.Json;
using System.IO;
using System.Threading;

namespace LeSoft.Application.Web.Areas.PropertyManage.Controllers
{
    public class SecurityPatrolController : MvcControllerBase
    {
        private SecurityPatrolItemBLL securityPatrolItemBLL = new SecurityPatrolItemBLL();
        private PollingBLL pollingBLL = new PollingBLL();
        private SecurityPatrolLineBLL securityPatrolLineBLL = new SecurityPatrolLineBLL();
        private SecurityPatrolLineDetailBLL securityPatrolLineDetailBLL = new SecurityPatrolLineDetailBLL();
        private SecurityPatrolResultBLL securityPatrolResultBLL = new SecurityPatrolResultBLL();
        private SecurityPatrolResultDetailBLL securityPatrolResultDetailBLL = new SecurityPatrolResultDetailBLL();
        private SecurityPatrolContentBLL securityPatrolContentBLL = new SecurityPatrolContentBLL();
        //
        // GET: /PropertyManage/SecurityPatrol/
        #region 视图

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult ResultIndex()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Form()
        {
            return View();
        }


        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult ItemIndex()
        {
            return View();
        }


        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult ItemForm()
        {
            return View();
        }


        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult AreaIndex()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult ContentIndex()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult ContentForm()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult ContentItemForm()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult ContentSelectContent()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult Detail()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult ContentDetail()
        {
            return View();
        }
        #endregion

        #region 查询数据

        /// <summary>
        /// 获取项目树形列表
        /// </summary>
        /// <param name="TypeId">TypeId</param>
        /// <returns>项目</returns>   
        [HttpGet]
        public ActionResult GetItemHtml(string OrganizeId)
        {
            var data = new SecurityPatrolItemBLL().GetItemList();
            if (!string.IsNullOrEmpty(OrganizeId)) data = data.Where(t => t.CompanyId == OrganizeId || t.CompanyId.IsEmpty()).ToList();
            StringBuilder sb = new StringBuilder();
            sb.Append("<li class='active' data-value='All'>所有</li><div class='divide'></div>");
            foreach (var item in data)
            {
                sb.Append("<li data-value='" + item.SPIId + "'>" + item.Name + "</li>");
            }
            return Content(sb.ToString());
        }
        /// <summary>
        /// 查询巡更点结果列表
        /// </summary>
        /// <param name="SPRId"></param>
        /// <param name="SPLId"></param>
        /// <returns></returns>
        public ActionResult GetResultDatile(Pagination pagination, string SPRId)
        {
            //var data = securityPatrolResultDetailBLL.GetList(SPRId).Join(securityPatrolLineDetailBLL.GetList(SPLId), x => x.SPLDId, y => y.SPLDId, (x, y) => new
            //{
            //    y.PStructId,
            //    y.PuctureFlag,
            //    y.Sort,
            //    y.SPContentId,
            //    x.ExecDate,
            //    x.ExecState,
            //    x.ExecMemo
            //}).Join(pollingBLL.GetList(), x => x.PStructId, y => y.PCode, (x, y) => new
            //{
            //    x.Sort,
            //    x.SPContentId,
            //    x.ExecMemo,
            //    x.ExecState,
            //    x.ExecDate,
            //    y.Name,
            //    y.PSAllName
            //}).OrderBy(t => t.Sort);
            var watch = CommonHelper.TimerStart();
            var data = securityPatrolResultDetailBLL.GetPointPageList(pagination, SPRId);
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }
        /// <summary>
        /// 查询巡更点内容
        /// </summary>
        /// <param name="SPRId"></param>
        /// <param name="SPLId"></param>
        /// <param name="PStructId"></param>
        /// <returns></returns>
        public ActionResult GetContentDetail(string SPRId, string SPLId, string PStructId)
        {
            var data = securityPatrolResultDetailBLL.GetContentPageList(SPRId, SPLId, PStructId);
            StringBuilder sb = new StringBuilder();
            sb.Append("<tbody>");
            if (data != null && data.Rows.Count > 0)
            {
                for (int i = 0; i < data.Rows.Count; i++)
                {
                    sb.Append("<tr style='border-bottom:1px dashed #CCC;'><td>" +
                            "<p><strong>" + (i + 1) + "." + data.Rows[i]["name"].ToString() + "</strong>  (标准要求：" + data.Rows[i]["criterion"].ToString() + "  检查方法：" + data.Rows[i]["checkway"].ToString() + ")</p><p></p>");
                    if (data.Rows[i]["type"].ToString() == "1")
                    {
                        List<PollingContentItemEntity> list = JsonConvert.DeserializeObject<List<PollingContentItemEntity>>(data.Rows[i]["typedescription"].ToString());
                        foreach (var content in list.OrderBy(t => t.Sort))
                        {
                            var str = data.Rows[i]["value"].ToString() == content.Value ? "checked" : "";
                            sb.Append("<div style=\"float: left; margin-left: 20px;\"><input type=\"radio\" " + str + " disabled=\"disabled\">" + content.Text + "</div>");
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(data.Rows[i]["scantime"].ToString()))
                        {
                            sb.Append("扫码时间：" + Convert.ToDateTime(data.Rows[i]["scantime"]).ToString("yyyy年MM月dd日 HH:mm:ss") + ",");
                        }
                        sb.Append("结果：" + data.Rows[i]["text"].ToString() + ",说明：" + data.Rows[i]["execmemo"].ToString() + "");
                    }
                    sb.Append(" <p></p></td></tr>");
                }
            }
            else
            {
                sb.Append("<tr><td>暂时没有数据</td></tr>");
            }
            sb.Append("</tbody>");
            return Content(sb.ToString());
        }

        /// <summary>
        /// 获取明细中的扫码实时图和扫码图还有视频
        /// </summary>
        /// <param name="SPRId"></param>
        /// <param name="PStructId"></param>
        /// <returns></returns>
        public ActionResult GetFileList(string SPRId, string PStructId)
        {
            var data = new AttachFileBLL().GetList(SPRId, new { OtherCode = PStructId }.ToJson());
            StringBuilder sb = new StringBuilder();
            StringBuilder sb1 = new StringBuilder();
            StringBuilder sb2 = new StringBuilder();
            if (data != null)
            {
                foreach (var item in data.Where(t => t.Type == 81 && t.FileType == 1))
                {
                    sb.Append("<li><img width='150px' height='150px' src=" + item.FileUrl + " title=" + item.FileName + "/></li>");
                }
                foreach (var item in data.Where(t => t.Type == 82 && t.FileType == 1))
                {
                    sb1.Append("<li><img width='150px' height='150px' src=" + item.FileUrl + " title=" + item.FileName + "/></li>");
                }
                foreach (var item in data.Where(t => t.Type == 81 && t.FileType == 3))
                {
                    sb2.Append("<li><video src='" + item.FileUrl + "' controls=\"controls\" width='150px' height='150px' title=" + item.FileName + "></video></li>");
                }
            }
            return Content(new { Img1 = sb.ToString(), Img2 = sb1.ToString(), Video = sb2.ToString() }.ToJson());
        }
        public ActionResult GetResultListJson(Pagination pagination, string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            int type = Convert.ToInt32(queryParam["type"]);
            DateTime EndTime = Convert.ToDateTime(queryParam["EndTime"]);
            DateTime StartTime = Convert.ToDateTime(queryParam["StartTime"]);
            string SPIId = queryParam["SPIId"].ToString();
            string OrganizeId = queryParam["OrganizeId"].ToString();
            IList<object> ColMs = new List<object>();
            int intervalDate = 0;
            string str = "[";
            int rows = 0, sum = 0, count = 0;
            var lineList = securityPatrolLineBLL.GetLineList().Join(securityPatrolItemBLL.GetItemList(), x => x.SPIId, y => y.SPIId, (x, y) => new
            {
                x.SPIId,
                x.Name,
                x.PStructId,
                x.CompanyId,
                y.Unit,
                y.UnitNum,
                y.Frequency,
                x.SPLId
            });
            if (!OperatorProvider.Provider.Current().IsSystem)
            {
                var organizeids = new OrganizeCache().GetSonOrganizeId(OperatorProvider.Provider.Current().CompanyId);
                lineList = lineList.Where(t => organizeids.Contains(t.CompanyId) || t.CompanyId.IsEmpty()).ToList();
            }
            if (!string.IsNullOrEmpty(SPIId) && SPIId != "All") lineList = lineList.Where(t => t.SPIId == SPIId).ToList();
            if (!string.IsNullOrEmpty(OrganizeId)) lineList = lineList.Where(t => t.CompanyId == OrganizeId || t.CompanyId.IsEmpty()).ToList();
            var datalist = lineList.Join(securityPatrolResultBLL.GetList(StartTime, EndTime), x => x.SPLId, y => y.SPLId, (x, y) => new
            {
                x.PStructId,
                PStructName = new PStructBLL().GetEntity(x.PStructId).Name,
                x.SPIId,
                x.Name,
                x.Unit,
                x.UnitNum,
                x.Frequency,
                y.SPRId,
                x.SPLId,
                y.ExecDate
            }).GroupBy(t => t.SPLId);
            switch (type)
            {
                case 1:
                    intervalDate = (EndTime - StartTime).Days;
                    if (datalist.Count() <= 0)
                    {
                        for (int i = 0; i <= intervalDate; i++)
                        {
                            DateTime date = StartTime.AddDays(i);
                            object colms = new object();
                            if (i == 0)
                            {
                                colms = new { label = "主键", name = "SPLId", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "项目主键", name = "SPIId", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "楼盘名称", name = "PStructName", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "线路名称", name = "Name", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "标准次数", name = "Frequency", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                            }
                            colms = new { label = date.ToString("yyyy-MM-dd") + "<br/>(" + Time.GetWeekNameOfDay(date) + ")", name = "Date" + i, width = 100, align = "center", sortable = false };
                            ColMs.Add(colms);
                            if (i == intervalDate)
                            {
                                colms = new { label = "小计", name = "Sum", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                            }
                        }
                    }
                    foreach (var item in datalist)
                    {
                        if (rows != 0)
                        {
                            str += ",";
                        }
                        str += "{\"SPLId\":\"" + item.Key + "\",";
                        if (item.FirstOrDefault() == null)
                        {
                            str += "\"SPIId\":\"\",\"PStructName\":\"\",\"Name\":\"\",\"Frequency\":\"";
                        }
                        else
                        {
                            var model = item.FirstOrDefault();
                            str += "\"SPIId\":\"" + model.SPIId + "\"," + "\"PStructName\":\"" + model.PStructName + "\"" + ",\"Name\":\"" + model.Name + "\"" + ",\"Frequency\":\"";
                            switch (model.Unit)
                            {
                                case 0: str += model.UnitNum + "天" + model.Frequency + "次\""; break;
                                case 1: str += model.UnitNum + "周" + model.Frequency + "次\""; break;
                                case 2: str += model.UnitNum + "月" + model.Frequency + "次\""; break;
                                case 3: str += model.UnitNum + "季" + model.Frequency + "次\""; break;
                                case 4: str += model.UnitNum + "年" + model.Frequency + "次\""; break;
                            }
                        }
                        for (int i = 0; i <= intervalDate; i++)
                        {
                            DateTime date = StartTime.AddDays(i);
                            if (rows == 0)
                            {
                                object colms = new object();
                                if (i == 0)
                                {
                                    colms = new { label = "主键", name = "SPLId", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "项目主键", name = "SPIId", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "楼盘名称", name = "PStructName", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "线路名称", name = "Name", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "标准次数", name = "Frequency", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                }
                                colms = new { label = date.ToString("yyyy-MM-dd") + "<br/>(" + Time.GetWeekNameOfDay(date) + ")", name = "Date" + i, width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                if (i == intervalDate)
                                {
                                    colms = new { label = "小计", name = "Sum", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                }
                            }
                            count = item.Count(t => t.ExecDate.Value.Date == date.Date);
                            sum += count;
                            str += ",\"Date" + i + "\":" + count;
                        }
                        str += ",\"Sum\":" + sum + "}";
                        sum = 0;
                        rows++;
                    }
                    break;
                case 2:
                    intervalDate = (EndTime.Month - StartTime.Month) + ((EndTime.Year - StartTime.Year) * 12);
                    if (datalist.Count() <= 0)
                    {
                        for (int i = 0; i <= intervalDate; i++)
                        {
                            DateTime date = StartTime.AddMonths(i);
                            object colms = new object();
                            if (i == 0)
                            {
                                colms = new { label = "主键", name = "SPLId", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "项目主键", name = "SPIId", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "楼盘名称", name = "PStructName", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "线路名称", name = "Name", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "标准次数", name = "Frequency", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                            }
                            colms = new { label = date.Year + "年" + date.Month + "月", name = "Date" + i, width = 90, align = "center", sortable = false };
                            ColMs.Add(colms);
                            if (i == intervalDate)
                            {
                                colms = new { label = "小计", name = "Sum", width = 90, align = "center", sortable = false };
                                ColMs.Add(colms);
                            }
                        }
                    }
                    foreach (var item in datalist)
                    {
                        if (rows != 0)
                        {
                            str += ",";
                        }
                        str += "{\"SPLId\":\"" + item.Key + "\",";
                        if (item.FirstOrDefault() == null)
                        {
                            str += "\"SPIId\":\"\",\"PStructName\":\"\",\"Name\":\"\",\"Frequency\":\"";
                        }
                        else
                        {
                            var model = item.FirstOrDefault();
                            str += "\"SPIId\":\"" + model.SPIId + "\"," + "\"PStructName\":\"" + model.PStructName + "\"" + ",\"Name\":\"" + model.Name + "\"" + ",\"Frequency\":\"";
                            switch (model.Unit)
                            {
                                case 0: str += model.UnitNum + "天" + model.Frequency + "次\""; break;
                                case 1: str += model.UnitNum + "周" + model.Frequency + "次\""; break;
                                case 2: str += model.UnitNum + "月" + model.Frequency + "次\""; break;
                                case 3: str += model.UnitNum + "季" + model.Frequency + "次\""; break;
                                case 4: str += model.UnitNum + "年" + model.Frequency + "次\""; break;
                            }
                        }
                        for (int i = 0; i <= intervalDate; i++)
                        {
                            DateTime date = StartTime.AddMonths(i);
                            if (rows == 0)
                            {
                                object colms = new object();
                                if (i == 0)
                                {
                                    colms = new { label = "主键", name = "SPLId", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "项目主键", name = "SPIId", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "楼盘名称", name = "PStructName", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "线路名称", name = "Name", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "标准次数", name = "Frequency", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                }
                                colms = new { label = date.Year + "年" + date.Month + "月", name = "Date" + i, width = 90, align = "center", sortable = false };
                                ColMs.Add(colms);
                                if (i == intervalDate)
                                {
                                    colms = new { label = "小计", name = "Sum", width = 90, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                }
                            }
                            count = item.Count(t => t.ExecDate.Value.Year == date.Year && t.ExecDate.Value.Month == date.Month);
                            sum += count;
                            str += ",\"Date" + i + "\":" + count;
                        }
                        str += ",\"Sum\":" + sum + "}";
                        sum = 0;
                        rows++;
                    }
                    break;
                case 3:
                    intervalDate = (EndTime.Year - StartTime.Year);
                    if (datalist.Count() <= 0)
                    {
                        for (int i = 0; i <= intervalDate; i++)
                        {
                            DateTime date = StartTime.AddYears(i);
                            object colms = new object();
                            if (i == 0)
                            {
                                colms = new { label = "主键", name = "SPLId", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "项目主键", name = "SPIId", hidden = true };
                                ColMs.Add(colms);
                                colms = new { label = "楼盘名称", name = "PStructName", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "线路名称", name = "Name", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                                colms = new { label = "标准次数", name = "Frequency", width = 100, align = "center", sortable = false };
                                ColMs.Add(colms);
                            }
                            colms = new { label = date.Year + "年", name = "Date" + i, width = 90, align = "center", sortable = false };
                            ColMs.Add(colms);
                            if (i == intervalDate)
                            {
                                colms = new { label = "小计", name = "Sum", width = 90, align = "center", sortable = false };
                                ColMs.Add(colms);
                            }
                        }
                    }
                    foreach (var item in datalist)
                    {
                        if (rows != 0)
                        {
                            str += ",";
                        }
                        str += "{\"SPLId\":\"" + item.Key + "\",";
                        if (item.FirstOrDefault() == null)
                        {
                            str += "\"SPIId\":\"\",\"PStructName\":\"\",\"Name\":\"\",\"Frequency\":\"";
                        }
                        else
                        {
                            var model = item.FirstOrDefault();
                            str += "\"SPIId\":\"" + model.SPIId + "\"," + "\"PStructName\":\"" + model.PStructName + "\"" + ",\"Name\":\"" + model.Name + "\"" + ",\"Frequency\":\"";
                            switch (model.Unit)
                            {
                                case 0: str += model.UnitNum + "天" + model.Frequency + "次\""; break;
                                case 1: str += model.UnitNum + "周" + model.Frequency + "次\""; break;
                                case 2: str += model.UnitNum + "月" + model.Frequency + "次\""; break;
                                case 3: str += model.UnitNum + "季" + model.Frequency + "次\""; break;
                                case 4: str += model.UnitNum + "年" + model.Frequency + "次\""; break;
                            }
                        }
                        for (int i = 0; i <= intervalDate; i++)
                        {
                            DateTime date = StartTime.AddYears(i);
                            if (rows == 0)
                            {
                                object colms = new object();
                                if (i == 0)
                                {
                                    colms = new { label = "主键", name = "SPLId", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "项目主键", name = "SPIId", hidden = true };
                                    ColMs.Add(colms);
                                    colms = new { label = "楼盘名称", name = "PStructName", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "线路名称", name = "Name", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                    colms = new { label = "标准次数", name = "Frequency", width = 100, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                }
                                colms = new { label = date.Year + "年", name = "Date" + i, width = 90, align = "center", sortable = false };
                                ColMs.Add(colms);
                                if (i == intervalDate)
                                {
                                    colms = new { label = "小计", name = "Sum", width = 90, align = "center", sortable = false };
                                    ColMs.Add(colms);
                                }
                            }
                            count = item.Count(t => t.ExecDate.Value.Year == date.Year);
                            sum += count;
                            str += ",\"Date" + i + "\":" + count;
                        }
                        str += ",\"Sum\":" + sum + "}";
                        sum = 0;
                        rows++;
                    }
                    break;
                default:
                    break;
            }
            str += "]";
            object obj = JsonConvert.DeserializeObject<object>(str);
            var coldata = new { total = rows, page = pagination.page, records = rows, rows = obj };
            var data = new { ColMs = ColMs, Coldata = coldata };
            return Content(data.ToJson());
        }

        public ActionResult GetResultList(Pagination pagination, DateTime StartTime, int AddDate, string SPLId, int type)
        {
            DateTime EndTime = new DateTime();
            switch (type)
            {
                case 1: StartTime = StartTime.AddDays(AddDate); EndTime = StartTime.AddDays(1).AddSeconds(-1); break;
                case 2: StartTime = StartTime.AddMonths(AddDate); EndTime = StartTime.AddMonths(1).AddSeconds(-1); break;
                case 3: StartTime = StartTime.AddYears(AddDate); EndTime = StartTime.AddYears(1).AddSeconds(-1); break;
                default:
                    break;
            }
            var queryJson = new { SPLId = SPLId, StartTime = StartTime, EndTime = EndTime }.ToJson();
            var resultData = securityPatrolResultBLL.GetPageList(pagination, queryJson);
            var watch = CommonHelper.TimerStart();
            var JsonData = new
            {
                rows = resultData,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }



        public ActionResult ExistItemName(string Name, string keyValue)
        {
            bool IsOk = securityPatrolItemBLL.ExistItemName(Name, keyValue);
            return Content(IsOk.ToString());
        }
        public ActionResult ExistEnCode(string Code, string keyValue)
        {
            bool IsOk = securityPatrolItemBLL.ExistItemCode(Code, keyValue);
            return Content(IsOk.ToString());
        }

        public ActionResult ExistLineName(string Name, string keyValue)
        {
            bool IsOk = securityPatrolLineBLL.ExistLineName(Name, keyValue);
            return Content(IsOk.ToString());
        }
        public ActionResult ExistLineCode(string Code, string keyValue)
        {
            bool IsOk = securityPatrolLineBLL.ExistLineCode(Code, keyValue);
            return Content(IsOk.ToString());
        }

        public ActionResult GetItemList(string condition, string keyword)
        {
            var data = securityPatrolItemBLL.GetItemList(condition, keyword);
            return Content(data.ToJson());
        }

        public ActionResult GetItemEntity(string keyValue)
        {
            var model = securityPatrolItemBLL.GetItemEntity(keyValue);
            return Content(model.ToJson());
        }

        public ActionResult GetList(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var dataLine = securityPatrolLineBLL.GetPageList(pagination, queryJson);
            var dataItem = securityPatrolItemBLL.GetItemList();
            //  var dataResult = securityPatrolResultBLL.GetList().GroupBy(t => t.SPLId);
            var list = dataLine.Join(dataItem, a => a.SPIId, b => b.SPIId, (a, b) => new
            {
                a.SPLId,
                PStructName = new PStructBLL().GetEntity(a.PStructId).Name,
                a.Name,
                a.Code,
                b.Frequency,
                b.Unit,
                b.UnitNum,
                IName = b.Name,
                ICode = b.Code
            });
            //var data = (from a in list
            //             join b in dataResult on a.SPLId equals b.Key
            //             into ab
            //             from b in ab.DefaultIfEmpty()
            //             select new
            //             {
            //                 a.SPLId,
            //                 a.Name,
            //                 a.Code,
            //                 a.IName,
            //                 a.ICode,
            //                 a.Frequency,
            //                 a.Unit,
            //                 a.UnitNum,
            //                 Count = b == null ? 0 : b.Count()
            //             }).ToList();
            var JsonData = new
                        {
                            rows = list,
                            total = pagination.total,
                            page = pagination.page,
                            records = pagination.records,
                            costtime = CommonHelper.TimerEnd(watch)
                        };
            return Content(JsonData.ToJson());
        }

        public ActionResult GetResult(string SPLId)
        {
            var data = securityPatrolResultBLL.GetList(SPLId);
            return Content(data.ToJson());
        }

        public ActionResult GetAreaList(string SPLId)
        {
            var dataArea = pollingBLL.GetList();
            var dataLineDetail = securityPatrolLineDetailBLL.GetList(SPLId);
            var dataResultDetail = securityPatrolResultDetailBLL.GetList();
            var list = dataLineDetail.Join(dataArea, a => a.PStructId, b => b.PCode, (a, b) => new
            {
                a.SPLDId,
                a.Sort,
                b.Name,
                b.FlagWay,
                b.FlagNo
            });
            var data = (from a in list
                        join b in dataResultDetail on a.SPLDId equals b.SPLDId
                        into ab
                        from b in ab.DefaultIfEmpty()
                        select new
                        {
                            a.SPLDId,
                            a.Sort,
                            a.Name,
                            a.FlagWay,
                            a.FlagNo,
                            Status = b == null ? 0 : b.ExecState,
                            Date = b == null ? null : b.ExecDate,
                            Memo = b == null ? "" : b.ExecMemo
                        }).ToList();
            return Content(data.ToJson());
        }

        public ActionResult GetAreaBySPLID(string SPLId)
        {
            var data = securityPatrolLineDetailBLL.GetList(SPLId).OrderBy(t => t.Sort);
            List<SecurityPatrolLineDetailEntity> list = new List<SecurityPatrolLineDetailEntity>();
            foreach (var item in data)
            {
                if (list.Count(t => t.Sort == item.Sort && t.PStructId == item.PStructId) > 0)
                {
                    list.Find(t => t.Sort == item.Sort && t.PStructId == item.PStructId).SPContentId += item.SPContentId + ",";
                    list.Find(t => t.Sort == item.Sort && t.PStructId == item.PStructId).SPLDId += item.SPLDId + ",";
                }
                else
                {
                    item.SPContentId += item.SPContentId == null ? "" : ",";
                    item.SPLDId += ",";
                    list.Add(item);
                }
            }
            var listdata = list.Join(pollingBLL.GetList(), x => x.PStructId, y => y.PCode, (x, y) => new
            {
                x.PuctureFlag,
                PuctureFlag1 = x.PuctureFlag == 1 || x.PuctureFlag == 3 ? 1 : 0,
                PuctureFlag2 = x.PuctureFlag == 2 || x.PuctureFlag == 3 ? 1 : 0,
                x.SPContentId,
                x.Sort,
                x.SPLDId,
                x.SPLId,
                y.EnCode,
                y.OtherCode,
                y.PCode,
                y.Name,
                y.PSAllName
            });
            return Content(listdata.ToJson());
        }

        public ActionResult GetLineEntity(string keyValue)
        {
            var model = securityPatrolLineBLL.GetLineEntity(keyValue);
            return Content(model.ToJson());
        }

        public ActionResult GetTreeListItem()
        {
            var data = securityPatrolItemBLL.GetItemList();
            var treeList = new List<TreeEntity>();
            foreach (SecurityPatrolItemEntity item in data)
            {
                TreeEntity tree = new TreeEntity();
                tree.id = item.SPIId;
                tree.text = item.Name;
                tree.value = item.SPIId;
                tree.isexpand = true;
                tree.complete = true;
                tree.hasChildren = false;
                tree.parentId = "0";
                tree.title = "item";
                treeList.Add(tree);
            }
            return Content(treeList.TreeToJson());
        }

        /// <summary>
        /// 根据楼盘ID查询公共区域
        /// </summary>
        /// <param name="PStructId"></param>
        /// <param name="Type"></param>
        /// <returns></returns>
        public ActionResult GetArea(string PStructId)
        {

            var PStruct = new PStructCache();
            var list = PStruct.RecursivePStruct(PStructId, "4");
            //var list = new PStructBLL().GetList().Where(t => t.Type == "6" && t.EnabledMark == 1).ToList();
            //if (!string.IsNullOrEmpty(PStructId))
            //{
            //    list = list.Where(t => t.AllCode.Contains(PStructId)).ToList();
            //}
            var data = list.Join(pollingBLL.GetList(), t => t.Id, y => y.PStructID, (t, y) => new
            {
                y.Name,
                y.PCode,
                y.PSAllName,
                y.EnCode,
                y.OtherCode
            });
            return Content(data.ToJson());

        }

        public ActionResult GetContentPageList(Pagination pagination, string queryJson)
        {

            var watch = CommonHelper.TimerStart();
            var dataLine = securityPatrolContentBLL.GetPageList(pagination, queryJson);
            if (!OperatorProvider.Provider.Current().IsSystem)
            {
                var organizeids = new OrganizeCache().GetSonOrganizeId(OperatorProvider.Provider.Current().CompanyId);
                dataLine = dataLine.Where(t => t.OrganizeId != null && organizeids.Contains(t.OrganizeId)).ToList();
            }
            var JsonData = new
            {
                rows = dataLine,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }

        public ActionResult GetContentList(string ids)
        {
            var dataLine = securityPatrolContentBLL.GetList();
            if (!OperatorProvider.Provider.Current().IsSystem)
            {
                var organizeids = new OrganizeCache().GetSonOrganizeId(OperatorProvider.Provider.Current().CompanyId);
                dataLine = dataLine.Where(t => t.OrganizeId != null && organizeids.Contains(t.OrganizeId)).ToList();
            }
            if (!string.IsNullOrEmpty(ids)) dataLine = dataLine.Where(t => ids.Contains(t.Id)).ToList();
            return Content(dataLine.ToJson());
        }

        public ActionResult GetContentEntity(string keyValue)
        {
            var model = securityPatrolContentBLL.GetEntity(keyValue);
            return Content(model.ToJson());
        }
        #endregion

        #region 保存数据
        public ActionResult SaveItemForm(string keyValue, SecurityPatrolItemEntity securityPatrolItemEntity)
        {
            securityPatrolItemBLL.SaveForm(keyValue, securityPatrolItemEntity);
            return Success("操作成功。");
        }

        public ActionResult RemoveItemForm(string keyValue)
        {
            securityPatrolItemBLL.RemoveForm(keyValue);
            return Success("删除成功。");
        }

        public ActionResult SaveForm(string keyValue, string SecurityPatrolLine, string SecurityPatrolLineDetail)
        {
            try
            {
                SecurityPatrolLineEntity securityPatrolLine = SecurityPatrolLine.ToObject<SecurityPatrolLineEntity>();
                List<SecurityPatrolLineDetailEntity> list = null;
                if (SecurityPatrolLineDetail != "[]")
                {
                    list = SecurityPatrolLineDetail.ToObject<List<SecurityPatrolLineDetailEntity>>();
                }
                securityPatrolLineBLL.SaveForm(keyValue, securityPatrolLine, list);
                return Success("操作成功。");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }

        }

        public ActionResult RemoveForm(string keyValue)
        {
            securityPatrolLineBLL.RemoveForm(keyValue);
            return Success("删除成功。");
        }

        public ActionResult SaveContentForm(string keyValue, SecurityPatrolContentEntity securityPatrolContentEntity)
        {
            securityPatrolContentBLL.SaveForm(keyValue, securityPatrolContentEntity);
            return Success("操作成功。");
        }
        public ActionResult RemoveContent(string keyValue)
        {
            securityPatrolContentBLL.RemoveForm(keyValue);
            return Success("删除成功。");
        }
        #endregion

        #region 上传设计图
        /// <summary>
        /// 上传设计图
        /// </summary>
        /// <param name="Filedata">文件对象</param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.Other, "上传设计图", "UploadifyFile")]
        public ActionResult UploadifyFile(HttpPostedFileBase Filedata)
        {
            try
            {
                Thread.Sleep(500);////延迟500毫秒
                //没有文件上传，直接返回
                if (Filedata == null || string.IsNullOrEmpty(Filedata.FileName) || Filedata.ContentLength == 0)
                {
                    return HttpNotFound();
                }
                //获取文件完整文件名(包含绝对路径)
                //文件存放路径格式：/Resource/ResourceFile/{userId}{data}/{guid}.{后缀名}
                string userId = OperatorProvider.Provider.Current().UserId;
                string fileGuid = Guid.NewGuid().ToString();
                long filesize = Filedata.ContentLength;
                string FileEextension = Path.GetExtension(Filedata.FileName);
                string uploadDate = DateTime.Now.ToString("yyyyMMdd");
                string virtualPath = string.Format("~\\PropertyManage\\SecurityPatrolFile\\{0}\\{1}\\{2}{3}", userId, uploadDate, fileGuid, FileEextension);
                string fullFileName = this.Server.MapPath(virtualPath);
                //创建文件夹
                string path = Path.GetDirectoryName(fullFileName);
                Directory.CreateDirectory(path);
                string FileUrl = "";
                if (!System.IO.File.Exists(fullFileName))
                {
                    //保存文件
                    Filedata.SaveAs(fullFileName);
                    string URL = Request.Url.ToString().Replace(Request.RawUrl, "/");
                    FileUrl = Server.MapPath(virtualPath).Replace(HttpRuntime.AppDomainAppPath, URL);
                }
                return Content(FileUrl);
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }
        #endregion
    }
}
